package com.block.source.service.receive;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.DualAuthorizationParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.service.ISourceReceiveService;
import com.block.test.reqbean.source.CheckUserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class CommonReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;

    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getAppSecret();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        // 请求数据解密
        String content = jsonObjectParamContent.getString("dataContent");
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(content);

        CheckUserInfo checkUserInfo = JSON.parseObject(paramContentData, CheckUserInfo.class);

        // 通过城市编码,获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddressInfoByCode(checkUserInfo.getCityCode());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        checkUserInfo.setCityCode(addressInfo.getCodeValue());
        checkUserInfo.setCity(addressInfo.getName());
        checkUserInfo.setProvinceCode(addressInfo.getParentCode());
        checkUserInfo.setProvince(addressInfo.getParentName());

        sourceApiResult.setCheckUserInfo(checkUserInfo);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getAppSecret();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (jsonObjectParamContent.isEmpty()){
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }
        String content = jsonObjectParamContent.getString("dataContent");
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(content);

        CheckUserInfo checkUserInfo = JSON.parseObject(paramContentData, CheckUserInfo.class);
        // TODO 多次查询注释; 240827
        // String orderNo = checkUserInfo.getOrderNo();
        // SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectById(orderNo);
        // if (pushResultInfo == null) {
        //     sourceApiResult.setReturnObject(this.getError("未找到撞库订单"));
        //     return sourceApiResult;
        // }
        // checkUserInfo.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setCheckUserInfo(checkUserInfo);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {

        SourceApiResult sourceApiResult = new SourceApiResult();

        SpecialCostomInfo specialCostomInfo = sourceApiParam.getSpecialCostomInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();

        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject returnObject = new JSONObject();
        returnObject.put("status", "000");
        returnObject.put("message", "撞库成功！");
        JSONObject dataObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        // 推送原价(分润渠道返回，固价渠道不返回)
        BigDecimal priceAmount = BigDecimal.ZERO;
        if (ObjectUtil.equals(ProfitSharingEnum.PROFITPRICE.getValue(), sourceBaseInfo.getPriceType())){
            priceAmount = pushResultInfo.getPriceAmount();//分润前价格

            // 如果是分润渠道，
            BigDecimal  settleAmount = NumberUtil.mul(priceAmount, BigDecimal.ONE.subtract(sourceBaseInfo.getPriceRate()));// 给上游结算金额
            if (settleAmount.compareTo(sourceBaseInfo.getCheckMinAmount()) < 0){
                // 结算金额 小于 设置的金额
                // 直接返回撞库失败
                returnObject.put("status", "501");
                returnObject.put("message", "订单金额小于"+sourceBaseInfo.getCheckMinAmount()+"；撞库失败");
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }

        }
        dataObject.put("price", priceAmount);
        dataObject.put("orderNo", pushResultInfo.getId() + "");
        dataObject.put("outOrderNo", pushResultInfo.getOutOrderNo());

        if (StrUtil.equals(specialCostomInfo.getInfoType(), InfoTypeEnum.APIS.getValue()) ){

            // 下游是 非 apis 类型
            dataObject.put("companyName", thirdBaseInfo.getCompanyName());
            String companyLogo = thirdBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", companyLogo);
            }

            dataObject.put("productName", thirdBaseInfo.getProductName());
            dataObject.put("maxLoanAmount", thirdBaseInfo.getMaxLoanAmount());
            dataObject.put("maxRate", thirdBaseInfo.getMaxLoanRate());
            dataObject.put("minRate", thirdBaseInfo.getMinLoanRate());

            //协议地址
            for (MerchantThirdProtocolInfo protocolInfo : thirdProtocolInfoList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("protocolName",protocolInfo.getProtocolName());
                jsonObject.put("protocolUrl", protocolInfo.getProtocolUrl());
                jsonArray.add(jsonObject);
            }
        }else{
            // 下游是 非 apis 类型
            dataObject.put("companyName", specialCostomInfo.getCompanyName());
            String companyLogo = specialCostomInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", specialCostomInfo.getCompanyLogo());
            }

            dataObject.put("productName", specialCostomInfo.getProductName());
            dataObject.put("maxLoanAmount", specialCostomInfo.getMaxLoanAmount());
            dataObject.put("maxRate", specialCostomInfo.getMaxRate());
            dataObject.put("minRate", specialCostomInfo.getMinRate());

            //协议地址

            JSONObject jsonObject = new JSONObject();
            ChannelInfo baseInfoByCode = channelCommonService.getChannelInfoCache(sourceBaseInfo.getChannelCode());
            ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByType(baseInfoByCode.getAppType());
            String protocolUrl = StrUtil.format("{}/page/user/newprotocol/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo());
            jsonObject.put("protocolName","授权协议");
            jsonObject.put("protocolUrl", protocolUrl);
            jsonArray.add(jsonObject);
        }

        dataObject.put("protocolList", jsonArray);
        returnObject.put("data", dataObject);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(resultInfoVO.isSuccess());

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("推送失败");
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("status", "500");
        returnObject.put("message", message);
        returnObject.put("data", new JSONObject());
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("status", "000");
        returnObject.put("message", "推送成功");
        returnObject.put("data", new JSONObject());
        return returnObject;
    }

    @Override
    public JSONObject resultInit(String channelCode, String reqId, String action) {
        return getSuccess();
    }

    @Override
    public JSONObject getError(JSONObject resultObj, String errCode, String errMsg) {
        return getError(errMsg);
    }

    @Override
    public JSONObject getError(JSONObject resultObj, String errMsg) {
        return getError(errMsg);
    }

    @Override
    public JSONObject getSuccess(JSONObject resultObj, JSONObject dataObj) {
        return getSuccess();
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam, String mobileMd5) {
        return null;
    }


}
